﻿
namespace Mulala.Cavan.Presentation.Mvc.Controller
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web.Mvc;
    using Mulala.Cavan.Application.MainBoundedContext.AttachmentModule;
    using Mulala.Cavan.Application.MainBoundedContext.CorporationModule;
    using Mulala.Cavan.Application.MainBoundedContext.MulalaModule;
    using Mulala.Cavan.Core.Extension;
    using Mulala.Cavan.Core.Helper;
    using Mulala.Cavan.Core.Message;
    using Mulala.Cavan.Domain.MainBoundedContext.AttachmentModule;
    using Mulala.Cavan.Domain.MainBoundedContext.CorporationModule;
    using Mulala.Cavan.Domain.MainBoundedContext.DictionaryModule;
    using Mulala.Cavan.Domain.MainBoundedContext.SearchModule;
    using Mulala.Cavan.Domain.MainBoundedContext.Setting;
    using Mulala.Cavan.Presentation.Mvc.ViewModel;
    using Mulala.Cavan.Presentation.Seedwork;
    using Newtonsoft.Json;

    public class CorporationController : EntityController<Corporation, CorporationSearch, ICorporationViewModel, ICorporationAppService>, ICorporationController
    {
        private IAttachmentAppService AttachmentAppService { get; set; }

        public CorporationController()
        {
            this.Model = ModelFactory.CreateModel<ICorporationViewModel>();
        }

        public override string ControllerName
        {
            get { return ControllerConst.CORPORATION; }
        }

        public override bool UseDenied
        {
            get { return false; }
        }

        [ActionName("detail")]
        public ActionResult GetCorporation(int id)
        {
            Corporation corporation = this.AppService.GetById(id);

            CorporationViewModelConverter.Convert(corporation, this.Model);
            this.SavaHistoryCorporation(this.Model);

            return View(this.Model);
        }

        [ActionName("similar")]
        [ChildActionOnly]
        public ActionResult GetCorporationsBySimilar(int id)
        {
            IDictionary<string, bool> orderBy = new Dictionary<string, bool>();
            orderBy.Add("EditTime", true);

            Corporation corporation = this.AppService.GetById(id);

            IList<Corporation> corporations = null;
            if (null != corporation)
            {
                CorporationSearch corporationSearch = CorporationSearchFactory.CreateCorporationSearch(corporation.Type, corporation.BusinessExperience, corporation.Scale, orderBy, 1, Project.Settings.SimilarCorporationAmount);
                corporations = this.AppService.GetBySearch(corporationSearch).ToList();
            }

            ICorporationsViewModel corporationsViewModel = CorporationViewModelConverter.Convert(corporations, false);
            if (null == corporations)
            {
                AppMessage message = new AppMessage(this, MessageSeverity.Info, "", "暂无相似家政公司");
                corporationsViewModel.Messages.Add(message);
            }

            return PartialView("~/Views/Corporation/_similarCorporationPartial.cshtml", corporationsViewModel);
        }

        [ActionName("list")]
        public ActionResult GetCorporationsByCondition(CorporationSearch corporationSearch)
        {
            long total = 0;
            IList<Corporation> corporations = this.AppService.GetBySearch(corporationSearch, out total).ToList();

            ICorporationsViewModel corporationsViewModel = CorporationViewModelConverter.Convert(corporations, true);
            corporationsViewModel.CorporationTotal = total;
            corporationsViewModel.SearchParam = corporationSearch;

            return View(corporationsViewModel);
        }

        [ActionName("search")]
        public ActionResult GetCorporationsByKeyword()
        {
            string keyword = this.HttpContext.Request["kw"].ToString();
            int currentPage = 1;
            int.TryParse(this.HttpContext.Request["cp"].ToString(), out currentPage);

            long total = 0;
            IList<Corporation> corporations = this.AppService.GetCorporationsByKeyword(keyword, currentPage, out total);

            ICorporationsViewModel corporationsViewModel = CorporationViewModelConverter.Convert(corporations, true);

            return View(corporationsViewModel);
        }

        [ActionName("greatecorporation")]
        [ChildActionOnly]
        public ActionResult GetCorporationBySystemRecommend()
        {
            IDictionary<string, bool> orderBy = new Dictionary<string, bool>();
            orderBy.Add("CorporationStatus.SystemRecommendTime", true);
            CorporationSearch corporationSearch = CorporationSearchFactory.CreateCorporationSearch(true, Project.Settings.GoldMinScore, Project.Settings.GoldMaxScore, orderBy, 1, Project.Settings.SystemRecommendCorporationAmount);

            Corporation corporation = this.AppService.GetSingleBySearch(corporationSearch);

            ICorporationViewModel corporationViewModel = ModelFactory.CreateModel<ICorporationViewModel>();
            CorporationViewModelConverter.Convert(corporation, corporationViewModel);

            return PartialView("~/Views/Corporation/_greateCorporationPartial.cshtml", corporationViewModel);
        }

        [ActionName("byclick")]
        [ChildActionOnly]
        public ActionResult GetCorporationsByClick()
        {
            IDictionary<string, bool> orderBy = new Dictionary<string, bool>();
            orderBy.Add("ViewTotal", true);
            CorporationSearch corporationSearch = CorporationSearchFactory.CreateCorporationSearch(orderBy, 1, Project.Settings.TopClickCorporationAmount);

            IList<Corporation> corporations = this.AppService.GetBySearch(corporationSearch).ToList();

            ICorporationsViewModel corporationsViewModel = CorporationViewModelConverter.Convert(corporations, false);

            return PartialView("~/Views/Corporation/_topClickCorporationPartial.cshtml", corporationsViewModel);
        }

        [ActionName("history")]
        [ChildActionOnly]
        public ActionResult GetCorporationsByHistory()
        {
            IHistoryCorporationsViewModel historyCorporationsViewModel = ModelFactory.CreateModel<IHistoryCorporationsViewModel>();
            if (CookieHelper.IsExsit(Project.Settings.MulalaHistoryCookieName))
            {
                string json = CookieHelper.GetCookie(MulalaAppServiceConst.HISTORYCORPORATION, Project.Settings.MulalaHistoryCookieName);
                historyCorporationsViewModel = JsonConvert.DeserializeObject<HistoryCorporationsViewModel>(json);
            }

            return PartialView("~/Views/Corporation/_historyCorporationPartial.cshtml", historyCorporationsViewModel);
        }

        [ActionName("photos")]
        public ActionResult GetCorporationPhotos(int id)
        {
            IList<Attachment> corporationPhotos = this.AttachmentAppService.GetCorporationPhotos(id);

            ICorporationPhotosViewModel corporationPhotosViewModel = CorporationPhotoViewModelConverter.Convert(corporationPhotos);

            return View(corporationPhotosViewModel);
        }

        [ActionName("goldcorporation")]
        [ChildActionOnly]
        public ActionResult GetCorporationByGold()
        {
            IDictionary<string, bool> orderBy = new Dictionary<string, bool>();
            orderBy.Add("UserAccount.Score", true);
            CorporationSearch corporationSearch = CorporationSearchFactory.CreateCorporationSearch(Project.Settings.GoldMinScore, Project.Settings.GoldMaxScore, orderBy, 1, Project.Settings.GoldCorporationAmount);

            IList<Corporation> corporations = this.AppService.GetBySearch(corporationSearch).ToList();

            ICorporationsViewModel corporationsViewModel = CorporationViewModelConverter.Convert(corporations, false);

            return PartialView("~/Views/Corporation/_goldCorporationPartial.cshtml", corporationsViewModel);
        }

        private void SavaHistoryCorporation(ICorporationViewModel corporation)
        {
            if (!CookieHelper.IsExsit(Project.Settings.MulalaHistoryCookieName))
            {
                CookieHelper.CreateCookie(Project.Settings.MulalaHistoryCookieName);
                CookieHelper.SetCookie(MulalaAppServiceConst.HISTORYCORPORATION, string.Empty, Project.Settings.MulalaHistoryCookieName);
            }
            string json = CookieHelper.GetCookie(MulalaAppServiceConst.HISTORYCORPORATION, Project.Settings.MulalaHistoryCookieName);
            IHistoryCorporationsViewModel historyCorporationsViewModel = ModelFactory.CreateModel<IHistoryCorporationsViewModel>();

            if (json.IsNotEmpty())
            {
                historyCorporationsViewModel = JsonConvert.DeserializeObject<HistoryCorporationsViewModel>(json);
                if (historyCorporationsViewModel.HistoryCorporations.Count + 1 > Project.Settings.HistoryCorporationAmount)
                {
                    IHistoryCorporationViewModel earliestCorporation = historyCorporationsViewModel.HistoryCorporations.OrderByDescending(hn => hn.ClickTime).First();
                    historyCorporationsViewModel.HistoryCorporations.Remove(earliestCorporation);
                }
            }

            IHistoryCorporationViewModel newCorporation = ModelFactory.CreateModel<IHistoryCorporationViewModel>();
            newCorporation.ClickTime = DateTime.Now;
            newCorporation.Logo = corporation.Logo;
            newCorporation.FullName = corporation.Item.FullName;
            newCorporation.Type = corporation.Type;
            newCorporation.DetailUrl = Project.Settings.HostServer + "/" + ControllerConst.CORPORATION + "/" + ActionConst.DETAIL + "/" + corporation.Item.ID.ToString();

            historyCorporationsViewModel.HistoryCorporations.Add(newCorporation);

            json = JsonConvert.SerializeObject(historyCorporationsViewModel);

            CookieHelper.SetCookie(MulalaAppServiceConst.HISTORYCORPORATION, json, Project.Settings.MulalaHistoryCookieName);
        }
    }
}
